package com.xu.tools.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author xuguan
 * @date 2023/2/12
 * @desc Spring容器工具类, 通过ApplicationListener<ContextRefreshedEvent>监听器实现
 */
@Component
public class ApplicationContext2Util implements ApplicationListener<ContextRefreshedEvent> {
    private static ApplicationContext ctx;

    public <T> T getBean(String name, Class<T> clazz) {
        return ctx.getBean(name, clazz);
    }

    public static Object getBean(String name) {
        return ctx.getBean(name);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ctx = contextRefreshedEvent.getApplicationContext();
    }
}
